package com.jwdf.uda.update;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.LogUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.umeng.message.PushAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 */
class CheckUpdateTask extends AsyncTask<Void, Void, String> {

    private ProgressDialog dialog;
    private Context mContext;
    private int mType;
    private UpdateVersionCallback mCallback;
    private boolean mShowProgressDialog;
    private static final String url = Constants.UPDATE_URL;
    private Map<String, Object> paramsMap = new HashMap<>();

    CheckUpdateTask(Context context, int type) {
        this.mContext = context;
        this.mType = type;

        paramsMap.put("version", AppUtils.getVersionName(context));
        paramsMap.put("build_num", AppUtils.getVersionCode(context));
        paramsMap.put("channel", AppContext.getChannel(context));
        paramsMap.put("platform", 2);
    }

    CheckUpdateTask(Context context, int type, boolean showProgressDialog) {
        this(context, type);
        this.mShowProgressDialog = showProgressDialog;
    }

    CheckUpdateTask(Context context, int type, UpdateVersionCallback callback) {
        this(context, type);
        this.mCallback = callback;
    }

    protected void onPreExecute() {
        if (mShowProgressDialog) {
            dialog = new ProgressDialog(mContext);
            dialog.setMessage(mContext.getString(R.string.android_auto_update_dialog_checking));
            dialog.show();
        }
    }


    @Override
    protected void onPostExecute(String result) {

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        if (!TextUtils.isEmpty(result)) {
            parseJson(result);
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.error_net), Toast.LENGTH_SHORT).show();
        }
    }

    private void parseJson(String result) {
        LogUtils.i(Constants.TAG, "Http post result:" + result);
        try {
            JSONObject obj = new JSONObject(result);
//            int isUpdate = obj.optInt(Constants.APK_IS_UPDATE);
            int isForce = obj.optInt(Constants.APK_IS_FORCE);
            String verson = obj.optString(Constants.APK_VERSION);
            String updateMessage = obj.optString(Constants.APK_UPDATE_CONTENT);
            String apkUrl = obj.optString(Constants.APK_DOWNLOAD_URL);
            int apkCode = obj.optInt(Constants.APK_VERSION_CODE);
            String apiUrl=obj.optString(Constants.API_URL);
            ConfigUtils.setApiUrl(mContext,UdaUtils.filterDoMainUrl(apiUrl));
            String uploadUrl=obj.optString(Constants.UPLOAD_URL);
            ConfigUtils.setUploadUrl(mContext, UdaUtils.filterDoMainUrl(uploadUrl));
            int versionCode = AppUtils.getVersionCode(mContext);
            if (apkCode > versionCode) {
                if (mType == Constants.TYPE_NOTIFICATION) {
                    showNotification(mContext, updateMessage, apkUrl);
                } else if (mType == Constants.TYPE_DIALOG) {
                    if (isForce > 0) {
                        showForceDialog(mContext, updateMessage, apkUrl,mCallback);
                    } else {
                        showDialog(mContext, updateMessage, apkUrl, mCallback);
                    }
                }
            } else {
                if (mCallback != null) {
                    mCallback.onLatestVersion();
                } else {
                    Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
                }
            }

        } catch (JSONException e) {
            Log.e(Constants.TAG, "parse json error");
            if (mCallback != null) {
                ConfigUtils.removeCurrentUser(mContext);
                ConfigUtils.setHttpHeadersCookie(mContext, "");
                PushAgent.getInstance(mContext).disable();
                UserEvent event = new UserEvent();
                event.setEvent(UserEvent.EVENT_LOGOUT);
                event.setExtra(mContext.getString(R.string.android_force_update_dialog_btn_cancel));
                EventBusUtil.post(event);
            } else {
                Toast.makeText(mContext, mContext.getString(R.string.error_parse), Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * Show dialog
     */
    private void showDialog(Context context, String content, String apkUrl, UpdateVersionCallback callback) {
        UpdateDialog.show(context, content, apkUrl, callback);
    }

    private void showForceDialog(Context context, String content, String apkUrl, UpdateVersionCallback callback) {
        UpdateDialog.showForceDialog(context, content, apkUrl,callback);
    }

    /**
     * Show Notification
     */
    private void showNotification(Context context, String content, String apkUrl) {
        Intent myIntent = new Intent(context, DownloadService.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        myIntent.putExtra(Constants.APK_DOWNLOAD_URL, apkUrl);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        int smallIcon = context.getApplicationInfo().icon;
        Notification notify = new NotificationCompat.Builder(context)
                .setTicker(context.getString(R.string.android_auto_update_notify_ticker))
                .setContentTitle(context.getString(R.string.android_auto_update_notify_content))
                .setContentText(content)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent).build();

        notify.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notify);
    }

    @Override
    protected String doInBackground(Void... args) {
        return HttpUtils.post(url, paramsMap);
    }
}
